<?php
/**
 * 第三方登陆
 *
 * @author andery
 */
namespace Common\Lib;
class oauth {
    private $_type = '';
    private $_setting = array();
    private $_error = '';
    public function __construct($name) {
        $this->_type = $name ? $name : 'qq';
        //加载登陆接口配置
		$oauth_list = YTATA_get_cache('oauth');
        $this->_setting = unserialize($oauth_list[$this->_type]['config']);
        //导入接口文件
        include_once COMMON_PATH . 'Lib/oauth/' . $this->_type . '/' . $this->_type . '.php';
        $om_class = $this->_type . '_oauth';
        $this->_om = new $om_class($this->_setting);
    }
    /**
     * 跳转到授权页面
     */
    public function authorize() {
        redirect($this->_om->getAuthorizeURL());
    }
    /**
     * 登陆回调
     */
    public function callbackLogin($request_args) {
        $user = $this->_om->getUserInfo($request_args);
        if(!$user){
            $this->_error = '用户信息获取失败！';
            return false;
        }
        $bind_user = $this->_checkBind($this->_type,$user['keyid']);
        if ($bind_user)
		{
            //登陆
           	if(D('User')->user_login('',$bind_user['uid'])){
			 $url ='user/index';
			}else{
			 $this->error('账号登录失败！');
			}	 
        }
		else
		{
            //处理用户名
            if(M('User')->where(array('username' => $user['keyname']))->getfield('uid')){
                $user['username'] = $user['keyname'] . '_' . mt_rand(99,9999);
            }else{
                $user['username'] = $user['keyname'];
            }
			//保存头像。经过测试效率太差！
            /* if($user['keyavatar_big']) {
                //下载原始头像到本地临时储存  用日期文件夹分类  方便清理
                $avatar_temp_root = C('YTATA_IMG_AVATAR_DIR') . 'temp/';
                $file_name = md5($user['keyid']) . '.jpg';
                if(!is_dir($avatar_temp_root)) mkdir($avatar_temp_root);
                $image_content = \Common\ORG\Http::fsockopenDownload($user['keyavatar_big']);
                file_put_contents($avatar_temp_root.$file_name, $image_content);
                $user['temp_avatar'] = $file_name;
            } */
            $user['bind_type'] = $this->_type;
            $user['bind_info']['keyname'] = $user['keyname'];
            $user['bind_info'] = $user['bind_info'];
            //把第三方的数据存到COOKIE
            session('user_bind_info',$user);
            $url = 'bind/binding';//第三方登录注册页
        }
        return U($url);
    }
    /**
     * 绑定回调
     */
    public function callbackBind($request_args) {
	
        !D('User')->is_login() && $this->redirect('user/index');
		
        $uid =session('ytata.uid');
        $user = $this->_om->getUserInfo($request_args);
        $bind_user = $this->_checkBind($this->_type, $user['keyid']);
        if ($bind_user['uid'] && $bind_user['uid'] == $uid) {
            $this->_error = '此帐号已经绑定过本站！';
            return false;
        }
        $user['uid'] = $uid;
        $user['bind_info']['keyname'] = $user['keyname'];
        if(false === $this->bindUser($user)){
            $this->_error = '帐号绑定失败，请重新操作！';
            return false;
        }
        return U('user/set_basic');
    }
    /**
     * 绑定帐号
     */
    public function bindUser($user) {
        $bind_user = array(
            'uid'           => $user['uid'],
            'type'          => $this->_type,
            'keyid'         => $user['keyid'],
            'info'          => !is_array($user['bind_info'])?$user['bind_info']:serialize($user['bind_info']),
            'bindingtime'   => time()
        );
        return M('UserBind')->add($bind_user);
    }
    /**
     * 检测用户是否已经绑定过本站
     */
    public function _checkBind($type, $key_id) {
        return M('UserBind')->where(array('type' => $type, 'keyid' => $key_id))->find();
    }
 
    /**
     * 返回需要的参数
     */
    public function NeedRequest() {
        return $this->_om->NeedRequest();
    }
    /**
     * 错误
     */
    public function getError(){
        return $this->_error;
    }
}